﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Models.DataAccess;
using springProject.Models;

namespace springProject.Controllers
{
    public class AdminController : Controller
    {
        Repository _repository;
        private readonly int PageContentSize;

        public AdminController()
        {
            _repository = new Repository();
            PageContentSize = 20;
        }

        public ActionResult Index()
        {
            return View();
        }

        public JsonResult ShowTree()
        {
            object[] jsonForSending;
            var parametres = Request.Params["nodeParams"].Split(' ');
            if (parametres != null && parametres.Length == 2)
            {
                Guid id;
                bool successId = Guid.TryParse(parametres[0], out id);
                int isFolder;
                bool successIsFolder = Int32.TryParse(parametres[1], out isFolder);

                var folders = _repository.GetAll<Folders>().Where(x => x.ParentId == null ? false : x.ParentId == id).ToList();
                var contents = _repository.GetAll<PageContent>().Where(x => x.Folder.FolderId == null ? false : x.Folder.FolderId == id).ToList();
                int count = folders.Count + contents.Count;
                jsonForSending = new object[count];

                int counter = 0;
                foreach(var item in folders)
                {
                    jsonForSending[counter++] = new { id = item.FolderId, title = item.FolderName, isFolder = 1, url = Url.Action("OpenFolder", new { id = item.FolderId }) };
                }
                foreach (var item in contents)
                {
                    jsonForSending[counter++] = new { id = item.ContentId, title = item.Summary, isFolder = 0, url = Url.Action("EditPageContent", new { id = item.ContentId }) };
                }
            }
            else
            {
                var folders = _repository.GetAll<Folders>().Where(x => x.ParentId == null).ToList();
                var contents = _repository.GetAll<PageContent>().Where(x => x.Folder.FolderId == null).ToList();
                int count = folders.Count + contents.Count;
                jsonForSending = new object[count];

                for (int i = 0; i < folders.Count; i++)
                {
                    jsonForSending[i] = new { id = folders[i].FolderId, title = folders[i].FolderName, isFolder = 1, url = Url.Action("OpenFolder", new { id = folders[i].FolderId }) };
                }
                for (int i = 0; i < contents.Count; i++)
                {
                    jsonForSending[i] = new { id = contents[i].ContentId, title = contents[i].Summary, isFolder = 0, url = Url.Action("OpenContent", new { id = contents[i].ContentId }) };
                }
            }

            return Json(jsonForSending, JsonRequestBehavior.AllowGet);
        }

        public ActionResult OpenFolder(Guid id, int pageNum = 0)
        {
            ViewData["FolderId"] = id;
            ViewBag.FolderName = _repository.GetById<Folders>(id).FolderName;
            
            var contentLinks = new List<FolderContent>();

            contentLinks.AddRange(_repository.GetAll<Folders>()
                                     .Where(pc => pc.ParentId == id)
                                     .Select(pc => new FolderContent
                                     {
                                         contentId = pc.FolderId,
                                         IsFolder = true,
                                         linkText = pc.FolderName
                                     }).OrderBy(f => f.linkText)
                                  );
            
            contentLinks.AddRange(_repository.GetAll<PageContent>()
                                     .Where(pc => pc.Folder.FolderId == id)
                                     .Select(pc => new FolderContent
                                     {
                                         contentId = pc.ContentId,
                                         IsFolder = false,
                                         linkText = pc.Summary.Length > 50 ? pc.Summary.Substring(0, 50) : pc.Summary
                                     }).OrderBy(c => c.linkText)
                                  );            
            
            ViewData["PageSize"] = PageContentSize;
            ViewData["PageNumber"] = pageNum;
            ViewData["PagesCount"] = contentLinks.Count;

            contentLinks = contentLinks
                .Skip(pageNum * PageContentSize)
                .Take(PageContentSize).ToList();

            return View(contentLinks);
        }

        [HttpGet]
        public ActionResult CreateFolder(Guid id)
        {
            return View();
        }

        [HttpPost]
        public ActionResult CreateFolder(Guid id, EditFolderModel editFolder)
        {
            editFolder.parentId = id;
            var folder = editFolder.ToFolders();
            _repository.Save<Folders>(folder);
            return RedirectToAction("OpenFolder", new { id = id });
        }

        [HttpGet]
        public ActionResult EditFolder(Guid id)
        {
            var model = new EditFolderModel(_repository.GetById<Folders>(id));
            return View(model);
        }

        [HttpPost]
        public ActionResult EditFolder(Guid id, EditFolderModel editFolder)
        {
            var folder = editFolder.ToFolders(_repository);
            _repository.Update<Folders>(folder);
            return RedirectToAction("OpenFolder", new { id = id });
        }

        [HttpGet]
        [ValidateInput(false)]
        public ActionResult CreatePageContent()
        {
            ViewBag.Folders = _repository.GetAll<Folders>();
            return View();
        }

        [HttpPost]
        public ActionResult CreatePageContent(CreatePage page)
        {           
            _repository.Save(page.ConvertToPageContent());
            return RedirectToAction("CreatePageContent");
        }
    }
}
